package com.mikao.config;

import com.alibaba.fastjson.JSON;
import com.mikao.constant.ErrorCode;
import com.mikao.dto.vo.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;


/**
 * @author KennyDavid
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        return new MethodValidationPostProcessor();
    }

    @ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BaseResult handler(ConstraintViolationException exception) {
        Set<ConstraintViolation<?>> constraintViolations = exception.getConstraintViolations();
        List<String> msg = new ArrayList<>();
        for (ConstraintViolation item : constraintViolations) {
            msg.add(item.getMessage());
        }
        BaseResult baseResult = BaseResult.builder()
                .code(ErrorCode.PARAM_ERROR.getCode())
                .msg(ErrorCode.PARAM_ERROR.getMsg())
                .errors(msg)
                .build();
        log.info("response  data: " + JSON.toJSONString(baseResult));
        log.info("======================Request end========================");
        return baseResult;
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = Exception.class)
    public BaseResult handleException(Exception e) {
        e.printStackTrace();
        return BaseResult.builder().code(HttpStatus.INTERNAL_SERVER_ERROR.value()).msg(e.getMessage()).build();
    }

}
